define(function(require, exports, module){
	
	/**
     * @name popStrategy
     * @class 封装投放策略的新建or修改弹框方法。
     * @requires classify, showmaterial
     */
	
	var requestUrl = {
			getResource: '/trp/strategy/get_resources/',
			getArea: '/trp/strategy/get_areas_tree/',
			getWord: '/trp/strategy/get_hotwords_tree/',
			getStrategy: '/trp/strategy/get_strategy/',
			getAlgorithm: '/trp/algorithm/get_release/',
			getOneInfo: '/trp/strategy/get_valid_resources/',
			submit: '/trp/strategy/create_or_update/'
		}
	
	popStrategy = function(option){
		var op = $.extend({
				type: '',			// 用户类型：platform | merchant
				action: 'add',		// 操作类型：add | edit
				strategy_id: '',	// 修改时填充数据用
				traffic_id: '',		// 新建时填充默认数据用
				resource_id: '',	// 新建时填充默认数据用
				isview: false,		// 是否查看
				width: '800px'
			}, option);
		
		if(semi.utils.isEmpty(op.type) || semi.utils.isEmpty(op.action))return;
		
		var isplatform = false, 
			isedit = false, 
			title = '新增策略', 
			strategy_id = '',
			resourceArr = {ids:[],nodes:[],badids:[]}, 
			areaArr = { submitNode:[], nodes:[], parents:[], data:[]}, 
			wordArr = { submitNode:[], nodes:[], parents:[], data:[]}, 
			materialArr = {materials:[], groups:[]},
			algorithmArr = {id:'', name:'', xml:'', json:''};
	    
		if(op.type=='platform'){
			isplatform = true;
    	}
    	if(!semi.utils.isEmpty(op.action) && op.action=='edit' && !semi.utils.isEmpty(op.strategy_id)){
    		isedit = true;
    		title = '修改策略';
    		strategy_id = op.strategy_id;
    	}
    	var defOp = {
        		id: 'popStrategyDlg',
                title: title,
                width: op.width,
                onshow: function(){
            		var $d = this, $node = $(this.node);
            		var checkData = function(){
            			if(semi.utils.isEmpty($('.daterangebox-ipt',$node).val()))return;
            			var date = $('.daterangebox-ipt',$node).val().split(' 至 ');
        	        	$('.checkedresource tbody tr',$node).each(function(){
        	        		var $this = $(this), _date =  $('.range',$this).text().split(' 至 '), resource_id = $this.attr('resource_id');
        	        		if(moment(_date[0]).diff(moment(date[1]))>0 || moment(_date[1]).diff(moment(date[0]))<0){
        	        			$this.addClass('red');
        	        			resourceArr.badids.pushOnly(resource_id);
        	        			$('td:first',$this).html('<span class="label label-danger" title="无效分片">周期不匹配</span>');
        	        		}else{
        	        			if($('.checkedmaterial [material_id]',$node).size()>0){
        	        				var _width = $('.width',$this).text(),
    	    	        				_height = $('.height',$this).text(), 
    	    	        				_max = parseInt($('.max',$this).text()), 
    	    	        				_typeArr = $('.type',$this).text().split(','),
    	    	        				_num = $('.checkedmaterial tbody tr',$node).size();
    	    	        			/*$('.checkedmaterial tbody tr',$node).each(function(){
    	    	        				var _name = $(this).find('.name').text(),
    	    	        					_suf = _name.substr(_name.length-3, 3).toUpperCase();
    	    	        				//if($(this).find('.width').text()==_width && $(this).find('.height').text()==_height && _typeArr.indexOf(_suf)!=-1)_num++;
    	    	        				if(_typeArr.indexOf(_suf.toUpperCase())!=-1)_num++;
    	    	        			});*/
    	    	        			if(_num<_max){
    	    	        				$this.addClass('red');
    	        	        			resourceArr.badids.pushOnly(resource_id);
    	        	        			$('td:first',$this).html('<span class="label label-danger" title="无效分片">匹配物料不足</span>');
    	    	        				return;	
    	    	        			}
        	        			}
        	        			$this.removeClass('red');
        	        			resourceArr.badids.remove(resource_id);
        	        			$('td:first',$this).html('<span class="glyphicon glyphicon-ok green" title="有效分片"></span>');
        	        		}
        	        		//素材
        	        		/*$('.checkedmaterial tbody tr',$node).each(function(){
    	        				var hasAd = false,
    	        					_name = $(this).find('.name').text(),
    	        					_suf = _name.substr(_name.length-3, 3).toUpperCase();
    	        				
    	        				$('.checkedresource tbody tr',$node).each(function(){
    	        					if($(this).find('.width').text()==_width && $(this).find('.height').text()==_height && _typeArr.indexOf(_suf)!=-1){
    	        						return true;
    	        					}
    	        				});
    	        				if(!hasAd){
        	        				$this.addClass('red');
            	        			//resourceArr.badids.pushOnly(resource_id);
            	        			//$('td:first',$this).html('<span class="label label-danger" title="无效分片">匹配物料不足</span>');
        	        			}
    	        				
    	        			});*/
        	        		
        	        	});
            		}
            		var initDialog = function(){
            			$('.daterangebox-ipt',$node).daterangepicker({
    	    	            format:'YYYY-MM-DD',
    	    	            minDate: moment().format("YYYY-MM-DD")
    	    	        }, checkData);
            			
            			$('[name=landingPage]',$node).on('focus', function(){
            				$(this).removeClass('error').siblings('label.error').remove();
            			})
            			
            			//媒体定向	resourceArr = {ids:[],nodes:[]}
                		$('.getresourcedata',$node).on('click', function(){
                			$(this).siblings('label.error').remove();
                			var $areaDlg = $dialog({
                				id: 'getresourcedataDlg',
                				title: '媒体定向',
                				zIndex: semi.utils.topIndex(),
                				content: ['<div class="pop-form pop-resource" style="overflow:auto;">',
                    				      	'<div class="pageheader">',
                    					    '<div class="searchbox pull-right">',
                    					        '<label>搜索<input id="term" class="searchbox-ipt" placeholder="按广告位称搜索" type="text"></label>',
                    					        '<a class="searchbox-btn" href="javascript:;"></a>',
                    					    '</div>',
                    					'</div>',
                    					'<div class="pagebox">',
                    						'<table class="grid">',
                    						    '<thead>',
                    						        '<tr>',
                    						        	'<th style="width:60px;"><input class="checkedall" type="checkbox" name="resource_ids"></th>',
                    						            '<th style="width:150px;">广告位名称</th>',
                    						            '<th style="width:150px;">购买周期</th>',
                    						            '<th style="width:50px;">宽</th>',
                    						            '<th style="width:50px;">高</th>',
                    						            '<th style="width:50px;">分栏数</th>',
                    						            '<th>素材类型</th>',
                    						            '<th>底价</th>',
                    						            '<th>所属媒体</th>',
                    						            '<th>时间</th>',
                    						            '<th>地域</th>',
                    						        '</tr>',
                    						    '</thead>',
                    						    '<tbody>',
                    						    	'<tr><td colspan="11" class="loading">&nbsp;</td></tr>',
                    						    '</tbody>',
                    						'</table>',
                    					'</div>',
                    				'</div>'].join(''),
                				width: op.width,
                				onshow: function(){
                					var _$d = this, _$node = $(this.node);
                					$('.grid',_$node).attr('id','resourceList');
                					var _bodyTemplate = ['<tr resource_id="{id}">',
                					                     	'<td class="txtc"><input type="checkbox" name="resource_id" tname="{name}" value="{id}"></td>',
    	            			    	                    '<td class="txtc">{name}</td>',
    	            			    	                    '<td class="txtc range">{start} 至 {end}</td>',
    	            			    	                    '<td class="txtc width">{width}</td>',
    	            			    	                    '<td class="txtc height">{height}</td>',
    	            			    	                    '<td class="txtc max">{max}</td>',
    	            			    	                    '<td class="txtc type">{type}</td>',
    	            			    	                    '<td class="txtc">{price}</td>',
    	            			    	                    '<td class="txtc">{media}</td>',
    	            			    	                    '<td class="txtc">{hours}</td>',
    	            			    	                    '<td class="txtc">{areas}</td>',
    	            				                     '</tr>'].join('');
                					
                					var pageTemplate = '<div class="gridTotal">共<b>{totalCount}</b>条记录</div>' +
    				            				        '<input type="button" value="首页" class="page-bt first-page" title="首页">' +
    				            				        '<input type="button" value="上一页" class="page-bt pre-page" title="上一页">' +
    				            				        '第{pageNo}页' +
    				            				        '<input type="button" value="下一页" class="page-bt next-page" title="下一页">' +
    				            				        '<input type="button" value="末页" class="page-bt last-page" title="末页">' +
    				            				        '共{totalPage}页'
                		    
    	            		    	var _grid = Grid.init({
    	            		            holder: 'resourceList',
    	            		            bodyTemplate: _bodyTemplate,
    	            		            dataSource: requestUrl.getResource,
    	            		            pageTemplate: pageTemplate,
    	            		            sendOnPageSize: true
    	            		        });
    	            		    	
                					_grid.modifyModel(function(data){
    	            		    		data.type = data.type.join(',');
    	            		    		
    	            		    		if(semi.utils.isEmpty(data.hours)){
    	            		    			data.hours = '默认';
    	            		    		}else if(data.hours.length==24){
    	            		    			data.hours = '全天';
    	            		    		}else{
    	            		    			data.hours = semi.utils.shorterNums(data.hours).join(',');
    	            		    		}
    	            		    		if(semi.utils.isEmpty(data.areas)){
    	            		    			data.areas = '默认';
    	            		    		}else{
    	            		    			data.areas = data.areas.join(',');
    	            		    		}
    	            		    	});
    	            		    	
    	            		    	_grid.onfilled(function(data){
    	            		    		$('#resourceList tbody tr').each(function(){
    	            		    			var _id = $(this).attr('resource_id');
    	            		    			if(resourceArr.ids.indexOf(_id)!=-1 && !semi.utils.isEmpty($(this).find('[name=resource_id]')[0])){
        	            		    			$(this).find('[name=resource_id]')[0].checked = true;
        	            		    		}
    	            		    		});
    	            		    		if($('#resourceList tbody [name=resource_id]:checked').size()==$('#resourceList tbody [name=resource_id]').size()){
    	            		    			$('#resourceList .checkedall')[0].checked = true;
    	            		    		}else{
    	            		    			$('#resourceList .checkedall')[0].checked = false;
    	            		    		}
    	            		    	});
    	            		        
    	            			    /* 数据搜索 */
    	            			    var _filterData = function(){
    	            			    	var txt = $('.searchbox-ipt',_$node).val(),
    	            			    		date = $('.daterangebox-ipt',$node).val().split(' 至 ');
    	            			    	
    	            			        _grid.send({
    	            			    		search_text: txt,
    	            			    		pageSize: 10,
    	            			    		start: date[0],
    	            			    		end: date[1],
    	            			    		pageNo: 1
    	            			    	});
    	            			    };
    	            			    _filterData();
    	            			    
    	            			  //按名称和标签模糊搜索
    	            		        $('.pageheader .searchbox-btn',_$node).on('click.classify', _filterData);
    	            		        $('.pageheader .searchbox-ipt',_$node).on('keyup', function(e){
    	            		        	if(e.keyCode==semi.keyCode.ENTER){
    	            		        		_filterData();
    	            		        	}
    	            		        });
    	            			    
    	            			    _$node.on('change', '.checkedall', function(){
    	            			    	if($(this)[0].checked){
    	            			    		$('#resourceList tbody [type=checkbox]').each(function(){
    	            			    			var _value = $(this).val(), 
        	            			    			_tr = $(this).parents('tr:first').clone().append('<td class="txtc"><span class="glyphicon glyphicon-minus" title="删除"></span></td>').find('td:first').html('<span class="glyphicon glyphicon-ok green" title="有效分片"></span>').end();
    	            			    			
    	            			    			$(this)[0].checked = true;
    	            			    			resourceArr.ids.pushOnly(_value);
        	            			    		resourceArr.nodes.pushOnly(_tr[0].outerHTML);
    	            			    		});
    	            			    	}else{
    	            			    		$('#resourceList tbody [type=checkbox]').each(function(){
    	            			    			var _value = $(this).val(), 
    	            			    				_tr = $(this).parents('tr:first').clone().append('<td class="txtc"><span class="glyphicon glyphicon-minus" title="删除"></span></td>').find('td:first').html('<span class="glyphicon glyphicon-ok green" title="有效分片"></span>').end();
    	            			    			
    	            			    			$(this)[0].checked = false;
    	            			    			resourceArr.ids.remove(_value);
    	            			    			var _index = -1;
    							    			$.each(resourceArr.nodes, function(i,n){
    							    				if(n.indexOf('resource_id="'+_value+'"')!=-1)_index=i;
    							    			});
    							    			if(_index!=-1)resourceArr.nodes.splice(_index,1);
        	            			    		//resourceArr.nodes.remove(_tr[0].outerHTML);
    	            			    		});
    	            			    	}
    	            			    });
    	            			    _$node.on('change', 'input[name=resource_id]', function(){
    	            			    	var _value = $(this).val(), 
    	            			    		_tr = $(this).parents('tr:first').clone().addClass('mouseover').append('<td class="txtc"><span class="glyphicon glyphicon-minus" title="删除"></span></td>').find('td:first').html('<span class="glyphicon glyphicon-ok green" title="有效分片"></span>').end();
    	            			    		
                			    		if($(this)[0].checked){
    	            			    		resourceArr.ids.pushOnly(_value);
    	            			    		resourceArr.nodes.pushOnly(_tr[0].outerHTML);
    	            			    	}else{
    	            			    		resourceArr.ids.remove(_value);
    	            			    		var _index = -1;
    						    			$.each(resourceArr.nodes, function(i,n){
    						    				if(n.indexOf('resource_id="'+_value+'"')!=-1)_index=i;
    						    			});
    						    			if(_index!=-1)resourceArr.nodes.splice(_index,1);
    	            			    		//resourceArr.nodes.remove(_tr[0].outerHTML);
    	            			    	}
    	            			    });
    	            			    if($('.pop-resource',_$node).width()>op.width)d.width($('.pop-resource',_$node).width()+40);
                				},
                				okValue: '确定',
                				ok: function(){
                            		var _$d = this, _$node = $(this.node);
                            		$('.getmaterialdata',$node).val('').data('materials',null);
                            		
                            		var $grid = $('.getresourcedata',$node).siblings('.checkedresource').show();
                            		$('tbody',$grid).empty();
                            		if(!semi.utils.isEmpty(resourceArr.nodes)){
                            			$grid.show();
                            			$.each(resourceArr.nodes, function(i,n){
                                			$('tbody',$grid).append(n);
                                			$('tbody tr:last',$grid).hoverClass('mouseover');
                                		});
                            		}else{
                            			$grid.hide();
                            		}
                            		var _ids = resourceArr.ids.join(','), _traIds = $('.getresourcedata',$node).siblings('[name=resourceids]');
                            		if(_ids!=_traIds.val()){
                            			//清空已素材
            				    		/*$('.checkedmaterial',$node).hide();
            				    		$('.getmaterialdata',$node).siblings('[name=material]').val('');
                                		materialArr.materials = [];
                                		materialArr.groups = [];*/
                            		}
                            		_traIds.val(_ids);
                            		checkData();
                            		_$d.close().remove();
                                },
                                cancelValue: '取消',
                                cancel: true
                			}).showModal();
                		});
                		$node.on('click', '.checkedresource .glyphicon-minus', function(){
                			var _tr = $(this).parents('tr:first'),
                				_value = _tr.attr('resource_id');
                			
    		    			resourceArr.ids.remove(_value);
    		    			var _index = -1;
    		    			$.each(resourceArr.nodes, function(i,n){
    		    				if(n.indexOf('resource_id="'+_value+'"')!=-1)_index=i;
    		    			});
    		    			if(_index!=-1)resourceArr.nodes.splice(_index,1);
    			    		
    			    		_tr.remove();
    			    		if($('.checkedresource tbody tr',$node).size()<1){
    			    			$('.checkedresource',$node).hide();
    			    			$('.getresourcedata',$node).siblings('[name=resourceids]').val('');
    			    		}
    			    		
    			    		//清空已素材
    			    		/*$('.checkedmaterial',$node).hide();
    			    		$('.getmaterialdata',$node).siblings('[name=material]').val('');
                    		materialArr.materials = [];
                    		materialArr.groups = [];*/
                			
                		});
                		
                		//地域定向	areaArr = {submitNode:[], nodes:[], parents:[], data:[]}
                		$('.getareadata',$node).on('click', function(){
                			var treeDlgOpened = false;
                			var $areaDlg = $dialog({
                				id: 'getareadataDlg',
                				title: '地域定向',
                				width: '400px',
                				zIndex: semi.utils.topIndex(),
                				onshow: function(){
                					var _$d = this, _$node = $(this.node);
                					var _initTree = function(){
                						require.async('ztree', function(){
                							var _treeData = semi.utils.clone(areaArr.data);
                							// 初始化选中
                							$.each(areaArr.submitNode, function(i,n){
                								var _index = -1;
                								$.each(_treeData, function(j,m){
            										if(n.id==m.id)_index = j;
            									});
                								if(_index==-1)return;
                								$.each(_treeData, function(j,m){
                									if(m.pId==n.id){
                										$.each(_treeData, function(k,o){
                											if(o.pId==m.id){
                												$.extend(o,{
                													checked: true
                												});
                											}
                										});
                										$.extend(m,{
                											checked: true
                										});
                									}
                								});
                								$.extend(_treeData[_index],{
                									checked: true
                								});
                                    		});
                							// 初始化展开
                							$.each(_treeData, function(i,n){
            									var len = 0; sub = 0;
            									$.each(_treeData, function(j,m){
            										if(m.pId==n.id){
            											if(m.checked){
            												sub++;
            											}
            											len++;
            										}
            									});
            									if(sub!=0){
            										$.extend(n,{
            											open: true,
            										});
            									}
            									if(len==sub){
            										$.extend(n,{
            											open: false,
            										});
            									}
                							});
                							//展开[中国]
                							$.extend(_treeData[0],{
                								open: true
                							});
                							
                							_$d.content('<div style="width:400px;height:300px;overflow:auto;"><input type="text" class="form-control ipt_search" placeholder="模糊搜索" style="position:absolute;top:-60px;left:140px;"/><ul id="areaTree" class="ztree"></ul></div>');
            								$.fn.zTree.init($('#areaTree'), {
            									data: {
        											simpleData: {
        												enable: true
        											}
        										},
                    							view: {
                    								fontCss: function(treeId, treeNode) {
                    									return (!!treeNode.highlight) ? {color:"#A60000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
                    								}
                    							},
                    							check: {
                    								enable: true,
                    								autoCheckTrigger: true
                    							}
                    						}, _treeData);
            								
            								/* 模糊搜索 */
                    						var treeObj = $.fn.zTree.getZTreeObj('areaTree'),
                    							lastValue = '',
                    							nodeList = [],
                    							updateNodes = function(highlight) {
                        							for( var i=0, l=nodeList.length; i<l; i++) {
                        								nodeList[i].highlight = highlight;
                        								treeObj.updateNode(nodeList[i]);
                        								treeObj.expandNode(nodeList[i].getParentNode(), true, false, false);
                        							}
                        						};
                    						
                    						$('.ipt_search',_$node).on({
                    							keyup: function(){
                        							var value = $(this).val().trim(),
                        								keyType = 'name';
                        							
                    								if(lastValue === value) return;
                    								lastValue = value;
                    								updateNodes(false);
                    								if(semi.utils.isEmpty(value)) return;
                    								nodeList = treeObj.getNodesByParamFuzzy(keyType, value);
                        							updateNodes(true);
                        						}
                    						});
        								});
                					}
                					if(semi.utils.isEmpty(areaArr.data)){
                						$ajax.ajax({
                							url: requestUrl.getArea,
                							success: function(treedata){
                								areaArr.data = treedata.data;
                								areaArr.data[0].pId = null;
                								_initTree();
                							}
                    					});
                					}else{
                						_initTree();
                					}
                				},
                				okValue: '确定',
                				ok: function(){
                            		var treeObj = $.fn.zTree.getZTreeObj('areaTree'),
    									checkedNodes = treeObj.getCheckedNodes();
                            		
                            		areaArr.submitNode = [], areaArr.nodes = [], areaArr.parents = [];
                            		$.each(checkedNodes, function(i,treeNode){
                            			var pNode = treeNode.getParentNode() , 
                            				node = {id:treeNode.id, name:treeNode.name, pId:treeNode.pId, parent:-1};
                        				if(!semi.utils.isEmpty(pNode)){
                        					node.parent = pNode.id;
                        					areaArr.parents.pushOnly(pNode);
                        				}
                        				areaArr.nodes.pushOnly(node);
                        				areaArr.submitNode.pushOnly({id:treeNode.id, name:treeNode.name});
                            		});
                            		if(semi.utils.isEmpty(areaArr.nodes))areaArr.parents = [];
                            		$.each(areaArr.parents, function(i,n){
                            			var length = 0;
                            			$.each(areaArr.nodes, function(j,m){
                                			if(m.parent==n.id)length++;
                                		});
                            			if(length==n.children.length){
                            				var allchecked = true;
                            				$.each(n.children, function(j,m){
                            					if(!semi.utils.isEmpty(m.children)){
                                        			$.each(m.children, function(k,o){
                                            			if(!o.checked)allchecked = false;
                                            		});
                                    			}
                            				});
                            				if(allchecked){
                            					$.each(areaArr.nodes, function(j,m){
                                        			if(m.parent==n.id){
                                        				areaArr.submitNode.remove({id:m.id, name:m.name});
                                        			}
                                        		});
                            				}else{
                            					areaArr.submitNode.remove({id:n.id, name:n.name});
                            				}
                            			}else{
                            				areaArr.submitNode.remove({id:n.id, name: n.name});
                            			}
                            		});
                            		
                            		var _nameArr = [];
                            		$.each(areaArr.submitNode, function(i,n){
                            			_nameArr.push(n.name);
                            		});
                            		$('.getareadata',$node).val(_nameArr.join('，'));
                                },
                                cancelValue: '取消',
                                cancel: true
                			}).showModal();
                		});
                		
                		//关键字定向	wordArr = {submitNode:[], nodes:[], parents:[], data:[]}
                		$('.getworddata',$node).on('click', function(){
                			var treeDlgOpened = false;
                			var $wordDlg = $dialog({
                				id: 'getworddataDlg',
                				title: '关键字定向',
                				width: '400px',
                				zIndex: semi.utils.topIndex(),
                				onshow: function(){
                					var _$d = this, _$node = $(this.node);
                					var _initTree = function(){
                						require.async('ztree', function(){
                							var _treeData = semi.utils.clone(wordArr.data);
                							// 初始化选中
                							$.each(wordArr.submitNode, function(i,n){
                								var _index = -1;
                								$.each(_treeData, function(j,m){
            										if(n.id==m.id)_index = j;
            									});
                								if(_index==-1)return;
                								$.each(_treeData, function(j,m){
                									if(m.id==n.pId){
                										$.extend(m,{
                											checked: true
                										});
                										$.each(_treeData, function(k,o){
                											if(o.id==m.pId){
                												$.extend(o,{
                													checked: true
                												});
                											}
                										});
                									}
                								});
                								$.extend(_treeData[_index],{
                									checked: true
                								});
                                    		});
                							// 初始化展开
                							/*$.each(_treeData, function(i,n){
            									var len = 0; sub = 0;
            									$.each(_treeData, function(j,m){
            										if(m.pId==n.id){
            											if(m.checked){
            												sub++;
            											}
            											len++;
            										}
            									});
            									if(sub!=0){
            										$.extend(n,{
            											open: true,
            										});
            									}
            									if(len==sub){
            										$.extend(n,{
            											open: false,
            										});
            									}
                							});*/
                							//展开
                							/*$.extend(_treeData[0],{
                								open: true
                							});*/
                							//关键字活跃度显示
                							$.each(_treeData, function(i,n){
                								if(!semi.utils.isEmpty(n.active) && n.active==1){
                									n['font'] = {'color':'red'};
                								}
                							});
                							if(semi.utils.isEmpty(_treeData)){
            									_$d.content('<span class="alert-warning"></span><span>暂无关键字！</span>');
            									_$d.button([{
            										value: '关闭'
            									}]);
            									return;
            								}
                							_$d.content('<div style="width:400px;height:300px;overflow:auto;"><input type="text" class="form-control ipt_search" placeholder="模糊搜索" style="position:absolute;top:-60px;left:140px;"/><ul id="wordTree" class="ztree"></ul></div>');
                							$.fn.zTree.init($('#wordTree'), {
            									data: {
        											simpleData: {
        												enable: true
        											}
        										},
                    							view: {
                    								fontCss: function(treeId, treeNode) {
                    									return (!!treeNode.highlight) ? {color:"#A60000", "font-weight":"bold"} : (treeNode.font ? $.extend({"font-weight":"normal"},treeNode.font) : {color:"#333", "font-weight":"normal"});
                    								}
                    							},
                    							check: {
                    								enable: true,
                    								autoCheckTrigger: true,
                    								chkboxType: { "Y" : "p", "N" : "p" }
                    							}
                    						}, _treeData);
            								
            								/* 模糊搜索 */
                    						var treeObj = $.fn.zTree.getZTreeObj('wordTree'),
                    							lastValue = '',
                    							nodeList = [],
                    							updateNodes = function(highlight) {
                        							for( var i=0, l=nodeList.length; i<l; i++) {
                        								nodeList[i].highlight = highlight;
                        								treeObj.updateNode(nodeList[i]);
                        								treeObj.expandNode(nodeList[i].getParentNode(), true, false, false);
                        							}
                        						};
                    						
                    						$('.ipt_search',_$node).on({
                    							keyup: function(){
                        							var value = $(this).val().trim(),
                        								keyType = 'name';
                        							
                    								if(lastValue === value) return;
                    								lastValue = value;
                    								updateNodes(false);
                    								if(semi.utils.isEmpty(value)) return;
                    								nodeList = treeObj.getNodesByParamFuzzy(keyType, value);
                        							updateNodes(true);
                        						}
                    						});
        								});
                					}
                					if(semi.utils.isEmpty(wordArr.data)){
                						$ajax.ajax({
                							url: requestUrl.getWord,
                							success: function(treedata){
                								wordArr.data = treedata.data;
                								//wordArr.data[0].pId = null;
                								_initTree();
                							}
                    					});
                					}else{
                						_initTree();
                					}
                				},
                				okValue: '确定',
                				ok: function(){
                            		var treeObj = $.fn.zTree.getZTreeObj('wordTree'),
    									checkedNodes = treeObj.getCheckedNodes();
                            		
                            		wordArr.submitNode = [], wordArr.nodes = [], wordArr.parents = [];
                            		$.each(checkedNodes, function(i,treeNode){
                            			var pNode = treeNode.getParentNode() , 
                            				node = {id:treeNode.id, name:treeNode.name, pId:treeNode.pId, parent:-1};
                        				if(!semi.utils.isEmpty(pNode)){
                        					node.parent = pNode.id;
                        					wordArr.parents.pushOnly(pNode);
                        				}
                        				wordArr.nodes.pushOnly(node);
                        				wordArr.submitNode.pushOnly({id:treeNode.id, name:treeNode.name, pId:treeNode.pId});
                            		});
                            		if(semi.utils.isEmpty(wordArr.nodes))wordArr.parents = [];
                            		$.each(wordArr.parents, function(i,n){
                            			var length = 0;
                            			$.each(wordArr.nodes, function(j,m){
                                			if(m.parent==n.id)length++;
                                		});
                            			if(length>0)wordArr.submitNode.remove({id:n.id, name: n.name, pId:n.pId});
                            			/*if(length==n.children.length){
                            				var allchecked = true;
                            				$.each(n.children, function(j,m){
                            					if(!semi.utils.isEmpty(m.children)){
                                        			$.each(m.children, function(k,o){
                                            			if(!o.checked)allchecked = false;
                                            		});
                                    			}
                            				});
                            				if(allchecked){
                            					$.each(wordArr.nodes, function(j,m){
                                        			if(m.parent==n.id){
                                        				wordArr.submitNode.remove({id:m.id, name:m.name, pId:m.pId});
                                        			}
                                        		});
                            				}else{
                            					wordArr.submitNode.remove({id:n.id, name:n.name, pId:n.pId});
                            				}
                            			}else{
                            				wordArr.submitNode.remove({id:n.id, name: n.name, pId:n.pId});
                            			}*/
                            		});
                            		
                            		//关键字回显
                            		var _nameArr = [], _ares = [], _words = [];
                            		$.each(wordArr.submitNode, function(i,n){
                            			_ares.push(n.id);
                					});
                            		$.each(wordArr.submitNode, function(i,n){
                            			var namepath = [n.name];
                            			$.each(wordArr.data, function(j,m){
                            				if(m.id==n.pId){
                            					namepath.push(m.name);
                            					$.each(wordArr.data, function(k,o){
                                    				if(o.id==m.pId){
                                    					namepath.push(o.name);
                                    				}
                                    			});
                            				}
                            			});
                            			_nameArr.push(namepath.reverse().join('-'));
                					});
                            		$('.getworddata',$node).val(_nameArr.join(','));
                                },
                                cancelValue: '取消',
                                cancel: true,
                                statusbar: '<span class="font12">注：红色为活跃关键字</span>'
                			}).showModal();
                		});
                		
                		
                		//时间定向
                		var _hours = [];
                		for(var i=0; i<4; i++){
                			$('.gettimedata [name=times]',$node).before('<div class="checktime" style="height:24px;position:relative;"><div class="btn-group btn-group-xs" style="display:inline-block;"></div><input type="checkbox" name="checktime" style="width:auto;position:absolute;right:-20px;top:7px;"></div>');
                			for(var j=0; j<6; j++){
                				$('.gettimedata .btn-group:last',$node).append('<button type="button" class="btn btn-default btn-info" time="'+(j+i*6)+'" style="width:50px;">'+(j+i*6)+':00</button>');
                				_hours.pushOnly(j+i*6);
                			}
                		}
                		var hours = $('.gettimedata',$node).data('hours');
                		if(semi.utils.isEmpty(hours)){
                			hours = _hours;
                			$('.gettimedata',$node).data('hours',hours);
                		}else{
                			$('.gettimedata [time]',$node).removeClass('btn-info');
                			$.each(hours, function(i,n){
                				$('.gettimedata [time='+n+']',$node).addClass('btn-info');
                			});
                		}
                		
                		$('.checktime',$node).each(function(){
                			var $this = $(this);
                			if($('.btn-info',$this).size()==$('.btn-default',$this).size()){
                				$('[name=checktime]',$this)[0].checked = true;
                			}else{
                				$('[name=checktime]',$this)[0].checked = false;
                			}
                		});
                		
                		$('.checktime [name=checktime]',$node).on('change', function(){
                			var $checktime = $(this).parents('.checktime:first'), _h = $('.gettimedata',$node).data('hours');
                			if($(this)[0].checked){
        			    		$('.btn-default',$checktime).each(function(){
        			    			$(this).addClass('btn-info');
        			    			_h.pushOnly(parseInt($(this).attr('time')));
        			    		});
        			    	}else{
        			    		$('.btn-default',$checktime).each(function(){
        			    			$(this).removeClass('btn-info');
        			    			_h.remove(parseInt($(this).attr('time')));
        			    		});
        			    	}
                		});
                		
                		$('.gettimedata .btn',$node).click(function(){
                			var t = parseInt($(this).attr('time')), _h = $('.gettimedata',$node).data('hours');
                			if($(this).hasClass('btn-info')){
                				$(this).removeClass('btn-info');
                				_h.remove(t);
                			}else{
                				$(this).addClass('btn-info');
                				_h.pushOnly(t);
                			}
                			$('.gettimedata [name=times]',$node).val(hours.join(''));
                			$('.checktime',$node).each(function(){
                    			var $this = $(this);
                    			if($('.btn-info',$this).size()==$('.btn-default',$this).size()){
                    				$('[name=checktime]',$this)[0].checked = true;
                    			}else{
                    				$('[name=checktime]',$this)[0].checked = false;
                    			}
                    		});
                		});
                		
                		/* 算法选择 */
                		if(!semi.utils.isEmpty(algorithmArr.id)){
                			var $formate = require('./formatxml'),
                				tmpl = $formate.gethtml(decodeURIComponent(algorithmArr.xml));
                			
                			$('.getalgorithm',$node).val(algorithmArr.name);
                			if(semi.utils.isEmpty(tmpl)){
                				$('.checkedalgorithm',$node).hide().find('.uicontent').empty();
                			}else{
                				$('.checkedalgorithm',$node).show().find('.uicontent').html(tmpl);
                				$formate.inithtml();
                				$formate.initjson($('.checkedalgorithm .uicontent',$node), algorithmArr.json);
                				$('.checkedalgorithm',$node).initUI();
                			}
                		}
                		$('.getalgorithm',$node).on('click', function(){
                			var $areaDlg = $dialog({
                				id: 'getalgorithmDlg',
                				title: '选择算法',
                				zIndex: semi.utils.topIndex(),
                				content: ['<div class="pop-form pop-algorithm">',
                    				      	'<div class="pageheader">',
                    					    '<div class="searchbox pull-right">',
                    					        '<label>搜索<input id="term" class="searchbox-ipt" placeholder="按算法名称模糊搜索" type="text"></label>',
                    					        '<a class="searchbox-btn" href="javascript:;"></a>',
                    					    '</div>',
                    					'</div>',
                    					'<div class="pagebox">',
                    						'<table class="grid" style="width:100%">',
                    						    '<thead>',
                    						        '<tr>',
                    						        	'<th style="width:60px;"><a class="clearbtn" href="javascript:;" title="空"><span class="glyphicon glyphicon-trash font12 gray"></span></a></th>',
                    						            '<th>算法名称</th>',
                    						            '<th>更新时间</th>',
                    						        '</tr>',
                    						    '</thead>',
                    						    '<tbody>',
                    						    	'<tr><td colspan="3" class="loading">&nbsp;</td></tr>',
                    						    '</tbody>',
                    						'</table>',
                    					'</div>',
                    				'</div>'].join(''),
                				width: op.width,
                				onshow: function(){
                					var _$d = this, _$node = $(this.node);
                					$('.grid',_$node).attr('id','algorithmList');
                					var _bodyTemplate = ['<tr algorithm_id="{id}">',
                					                     	'<td class="txtc"><input type="radio" name="algorithm_id" tname="{name}" value="{id}"><input type="hidden" name="xml" value="{xml_format}"></td>',
    	            			    	                    '<td class="txtc name">{name}</td>',
    	            			    	                    '<td class="txtc">{time}</td>',
    	            				                     '</tr>'].join('');
                					
                					var pageTemplate = '<div class="gridTotal">共<b>{totalCount}</b>条记录</div>' +
    				            				        '<input type="button" value="首页" class="page-bt first-page" title="首页">' +
    				            				        '<input type="button" value="上一页" class="page-bt pre-page" title="上一页">' +
    				            				        '第{pageNo}页' +
    				            				        '<input type="button" value="下一页" class="page-bt next-page" title="下一页">' +
    				            				        '<input type="button" value="末页" class="page-bt last-page" title="末页">' +
    				            				        '共{totalPage}页'
                		    
    	            		    	var _grid = Grid.init({
    	            		            holder: 'algorithmList',
    	            		            bodyTemplate: _bodyTemplate,
    	            		            dataSource: requestUrl.getAlgorithm,
    	            		            pageTemplate: pageTemplate,
    	            		            sendOnPageSize: true
    	            		        });
                					_grid.modifyModel(function(data){
                			        	data.time = data.time.replace('T',' ');
                			    	});
    	            		    	_grid.onfilled(function(data){
    	            		    		if(!semi.utils.isEmpty(algorithmArr.id)){
    	            		    			$('.glyphicon-trash').addClass('red').attr('title','清空已选：'+algorithmArr.name);
    	            		    			var _n = $('#algorithmList tbody tr[algorithm_id='+algorithmArr.id+'] input[name=algorithm_id]')[0];
    	            		    			if(!semi.utils.isEmpty(_n))_n.checked = true;
    	            		    		}else{
    	            		    			$('.glyphicon-trash').removeClass('red').attr('title','空');
    	            		    		}
    	            		    	});
    	            		        
    	            			     //数据搜索 
    	            			    var _filterData = function(){
    	            			    	var txt = $('.searchbox-ipt',_$node).val(),
    	            			    		date = $('.daterangebox-ipt',$node).val().split(' 至 ');
    	            			    	
    	            			        _grid.send({
    	            			    		search_text: txt,
    	            			    		pageSize: 10,
    	            			    		pageNo: 1
    	            			    	});
    	            			    };
    	            			    _filterData();
    	            			    
    	            			  //按名称和标签模糊搜索
    	            		        $('.pageheader .searchbox-btn',_$node).on('click.classify', _filterData);
    	            		        $('.pageheader .searchbox-ipt',_$node).on('keyup', function(e){
    	            		        	if(e.keyCode==semi.keyCode.ENTER){
    	            		        		_filterData();
    	            		        	}
    	            		        });
    	            			    
    	            		        _$node.on('change', 'input[name=algorithm_id]', function(){
    	            			    	var _$tr = $(this).parents('tr:first');
    	            			    	algorithmArr.id = $(this).val();
    	            			    	algorithmArr.name = $('.name',_$tr).text();
    	            			    	algorithmArr.xml = $('[name=xml]',_$tr).val();
    	            			    	$('.glyphicon-trash').addClass('red').attr('title','清空已选：'+algorithmArr.name);
    	            			    }).on('click', '.clearbtn', function(){
    	            			    	if($('#algorithmList input[name=algorithm_id]:checked').size()>0)$('#algorithmList input[name=algorithm_id]:checked')[0].checked = false;
    	            			    	algorithmArr.id = '';
    	            			    	algorithmArr.name = '';
    	            			    	algorithmArr.xml = '';
    	            			    	$('.glyphicon-trash').removeClass('red').attr('title','空');
    	            			    });
                				},
                				okValue: '确定',
                				ok: function(){
                            		var _$d = this, 
                            			_$node = $(this.node),
                            			$formate = require('./formatxml'),
                            			tmpl = $formate.gethtml(decodeURIComponent(algorithmArr.xml));
                            		
                            		$('.getalgorithm',$node).val(algorithmArr.name);
            						if(semi.utils.isEmpty(tmpl)){
            							$('.checkedalgorithm',$node).hide().find('.uicontent').empty();
            						}else{
            							$('.checkedalgorithm',$node).show().find('.uicontent').html(tmpl);
            							$formate.inithtml();
            							$('.checkedalgorithm',$node).initUI();
            						}
                            		_$d.close().remove();
                                },
                                cancelValue: '取消',
                                cancel: true
                			}).showModal();
                		});
                		
                		/* 素材选择 */
                		$('.getmaterialdata',$node).on('click', function(){
                			var data = {resource_ids: resourceArr.ids};
                			$(this).siblings('label.error').remove();
                			if(semi.utils.isEmpty(data.resource_ids)){
            					$dialog.alert('请先确定媒体定向！','warning');
            					return
            				}
                    		if(isedit){
                    			data.strategy_id = strategy_id;
                    		}
                			$ajax.ajax({
                        		url:'/static/trp/template/classify.html',
                        		success: function(html){
                        			require.async('./classify', function($classify){
                        				$dialog({
                        					id: 'getmaterialdataDlg',
                            	        	title: '素材选择',
                            	        	content: html,
                            				zIndex: semi.utils.topIndex(),
                            	        	onshow: function(){
                            	        		$classify.init({
                            	        			data: data,
                            	        			getgroup: 0,
                            	        			groups: materialArr.groups
                            	        		});
                            	        	},
                            	        	okValue: '确定',
                                        	ok: function(){
                                        		var _$d = this, _$node = $(this.node);
                                        		if(!$classify.check())return false;
                                        		var _html = $classify.gethtml();
                                        		if(!semi.utils.isEmpty(_html)){
                                        			var $grid = $('.checkedmaterial',$node).show();
                                        			$('tbody',$grid).empty().append(_html);
                                        			$('tbody tr:last',$grid).hoverClass('mouseover');
                                        			$('.getmaterialdata',$node).siblings('[name=material]').val('hasmaterial');
                                        		}else{
                                        			$('.checkedmaterial',$node).hide().find('tobdy').empty();
                                        			$('.getmaterialdata',$node).siblings('[name=material]').val('');
                                        		}
    		                            		
                                        		materialArr.materials = $classify.get(true);
                                        		materialArr.groups = $classify.get();
                                        		checkData();
                                            },
                                            cancelValue: '取消',
                                            cancel: function(){}
                            	        }).showModal();
                        			});
                        		}
                        	});
                		});
                		$node.on('click', '.checkedmaterial .glyphicon-minus', function(){
                			var _tr = $(this).parents('tr:first'), _id = _tr.attr('material_id'), _index = -1, _index2 = -1, _index3 = -1;
                			$.each(materialArr.materials, function(i,n){
                				if(n.material_id==_id)_index=i;
                			});
                			if(_index!=-1)materialArr.materials.splice(_index,1);
                			$.each(materialArr.groups, function(i,n){
                				_index = i
                				$.each(n.materials, function(k,m){
                    				if(m.id==_id){_index2 = i;_index3 = k;}
                    			});
                			});
                			if(_index3!=-1){
                				materialArr.groups[_index2].materials.splice(_index3,1);
                				if(semi.utils.isEmpty(materialArr.groups[_index2].materials)){
                					if(_index2!=0){
                						materialArr.groups[0].weight += materialArr.groups[_index2].weight;
                						_tr.siblings('[gname='+materialArr.groups[0].name+']').find('.gweight').text(materialArr.groups[0].weight);
                						materialArr.groups[0].name
                					}
                					materialArr.groups.splice(_index2,1);
                				}
                			}
                			_tr.remove();
                			if($('.checkedmaterial .glyphicon-minus',$node).size()<1){
                				$('.checkedmaterial',$node).hide();
                				$('.getmaterialdata',$node).siblings('[name=material]').val('');
                			}
                			checkData();
                		});
                		
                		//平滑消耗开关
                		/*$('.consume_type_in .btn,.consume_type_out .btn,.consume_type_ally .btn').on('click', function(){
                			if($(this).hasClass('state_open')){
                				$(this).addClass('btn-success').siblings('.btn').removeClass('btn-danger');
                			}else{
                				$(this).addClass('btn-danger').siblings('.btn').removeClass('btn-success');
                			}
                        });*/
                		$('.consume_type_in .btn').on('click', function(){
                			if($(this).hasClass('state_open')){
                				var _val1 = $('[name=dailyAmountIn]',$node).val(),
        							_val2 = $('[name=dailyBudgetIn]',$node).val();
                				if(isplatform){
                					if(_val1=='' || _val1==0){
                    					$dialog.alert('请先设置【站内日投放量控制】','warning');
                    					return;
                    				}
                				}else{
                					if((_val1=='' || _val1==0) && (_val2=='' || _val2==0)){
                    					$dialog.alert('请先设置【站内日投放预算】或【站内日投放量控制】','warning');
                    					return;
                    				}
                				}
                				$(this).addClass('btn-success').siblings('.btn').removeClass('btn-danger');
                			}else{
                				$(this).addClass('btn-danger').siblings('.btn').removeClass('btn-success');
                			}
                        });
                		$('.consume_type_out .btn').on('click', function(){
                			if($(this).hasClass('state_open')){
                				var _val1 = $('[name=dailyAmountOut]',$node).val(),
    								_val2 = $('[name=dailyBudgetOut]',$node).val();
                				if(isplatform){
                					if(_val1=='' || _val1==0){
                    					$dialog.alert('请先设置【站外日投放量控制】','warning');
                    					return;
                    				}
                				}else{
                					if((_val1=='' || _val1==0) && (_val2=='' || _val2==0)){
                    					$dialog.alert('请先设置【站外日投放预算】或【站外日投放量控制】','warning');
                    					return;
                    				}
                				}
                				$(this).addClass('btn-success').siblings('.btn').removeClass('btn-danger');
                			}else{
                				$(this).addClass('btn-danger').siblings('.btn').removeClass('btn-success');
                			}
                        });
                		$('.consume_type_ally .btn').on('click', function(){
                			if($(this).hasClass('state_open')){
                				var _val1 = $('[name=dailyAmountAlly]',$node).val(),
    								_val2 = $('[name=dailyBudgetAlly]',$node).val();
                				if(isplatform){
                					if(_val1=='' || _val1==0){
                    					$dialog.alert('请先设置【联盟日投放量控制】','warning');
                    					return;
                    				}
                				}else{
                					if((_val1=='' || _val1==0) && (_val2=='' || _val2==0)){
                    					$dialog.alert('请先设置【联盟日投放预算】或【联盟日投放量控制】','warning');
                    					return;
                    				}
                				}
                				$(this).addClass('btn-success').siblings('.btn').removeClass('btn-danger');
                			}else{
                				$(this).addClass('btn-danger').siblings('.btn').removeClass('btn-success');
                			}
                        });
                		
                		$('[name=dailyAmountIn],[name=dailyBudgetIn]',$node).on('blur', function(){
                			var _val1 = $('[name=dailyAmountIn]',$node).val(), 
                				_val2 = $('[name=dailyBudgetIn]',$node).val();
                			if((isplatform || (_val2=='' || _val2==0)) && (_val1=='' || _val1==0)){
                				$('.consume_type_in .state_close').addClass('btn-danger').siblings('.btn').removeClass('btn-success');
            				}
                		});
                		$('[name=dailyAmountOut],[name=dailyBudgetOut]',$node).on('blur', function(){
                			var _val1 = $('[name=dailyAmountOut]',$node).val(), 
    	        				_val2 = $('[name=dailyBudgetOut]',$node).val();
                			if((isplatform || (_val2=='' || _val2==0)) && (_val1=='' || _val1==0)){
                				$('.consume_type_out .state_close').addClass('btn-danger').siblings('.btn').removeClass('btn-success');
            				}
                		});
                		$('[name=dailyAmountAlly],[name=dailyBudgetAlly]',$node).on('blur', function(){
                			var _val1 = $('[name=dailyAmountAlly]',$node).val(), 
    	        				_val2 = $('[name=dailyBudgetAlly]',$node).val();
                			if((isplatform || (_val2=='' || _val2==0)) && (_val1=='' || _val1==0)){
                				$('.consume_type_ally .state_close').addClass('btn-danger').siblings('.btn').removeClass('btn-success');
            				}
                		});
                		
                		//指标控制
                		$('.typedata input[type=text]',$node).on('keyup', function(){
                			var _val = $(this).val();
                			if(!/^\d+$/.test(_val)){
                				var __val = _val+'';
                				$(this).val(__val.substr(0,__val.length-1));
                			}
                		});
                		
            		}
            		
            		$ajax.ajax({
            			url: '/static/trp/template/popstrategy.html',
            			success: function(popTmpl){
            				if(isplatform){
            					popTmpl = $(popTmpl).find('.forplatform').show().end().find('.formerchant').remove().end()[0].outerHTML;
            					//$('.formerchant',$node).remove();
            					//$('.forplatform',$node).show();
            				}else{
            					popTmpl = $(popTmpl).find('.formerchant').show().end().find('.forplatform').remove().end()[0].outerHTML;
            					//$('.forplatform',$node).remove();
            					//$('.formerchant',$node).show();
            				}
            				if(isedit){
                    			$ajax.ajax({
                    				url: requestUrl.getStrategy,
                    				data: {
                    					id: strategy_id
                    				},
                    				success: function(data){
                    					$d.content(popTmpl);
                    					if(isplatform){
                        					//$('.formerchant',$node).remove();
                        					//$('.forplatform',$node).show();
                        				}else{
                        					//$('.forplatform',$node).remove();
                        					//$('.formerchant',$node).show();
                        					$('[name=dailyBudgetIn]',$node).val(data.dailyBudgetIn);
                        					$('[name=dailyBudgetOut]',$node).val(data.dailyBudgetOut);
                        					$('[name=dailyBudgetAlly]',$node).val(data.dailyBudgetAlly);
                        					$('[name=totalBudgetIn]',$node).val(data.totalBudgetIn);
                        					$('[name=totalBudgetOut]',$node).val(data.totalBudgetOut);
                        					$('[name=totalBudgetAlly]',$node).val(data.totalBudgetAlly);
                        					$('[name=price]',$node).val(data.price);
                        				}
                    					$('[name=dailyAmountIn]',$node).val(data.dailyAmountIn);
                    					$('[name=dailyAmountOut]',$node).val(data.dailyAmountOut);
                    					$('[name=dailyAmountAlly]',$node).val(data.dailyAmountAlly);
                    					$('[name=totalAmountIn]',$node).val(data.totalAmountIn);
                    					$('[name=totalAmountOut]',$node).val(data.totalAmountOut);
                    					$('[name=totalAmountAlly]',$node).val(data.totalAmountAlly);
                    					$('[name=landingPage]',$node).val(decodeURIComponent(data.landingPage));
                    					$('[name=circle]',$node).val(data.start+' 至 '+data.end);
                    					if(!semi.utils.isEmpty(op.state) && op.state=='投放中'){
                    						semi.utils.getSTime(function(time){
                    							$('[name=circle]',$node).daterangepicker({
                            			            format:'YYYY-MM-DD',
                            			            minDate: time,
                            			            //maxDate: data.end,
                            			            freezeLeft: true
                            			        });
                    						});
                    					}
                    					
                    					$('[name=name]',$node).val(data.name);
                    					
                    					//媒体定向 
                    					//var _tmpResource = [{resource_id:50, position_name:'media 5 position 10', start:'2014-01-01', end:'2014-12-31', width:'200', height:'100', type:'PNG、JPG、GIF、BMP', floor:'1', media_name:'media 5'}]
                    					var _tmpl_media = '<tr resource_id="{resource_id}"><td class="txtc"><span class="glyphicon glyphicon-ok green" title="有效分片"></span></td><td class="txtc">{position_name}</td><td class="txtc range">{start} 至 {end}</td><td class="txtc width">{width}</td><td class="txtc height">{height}</td><td class="txtc max">{max}</td><td class="txtc type">{type}</td><td class="txtc">{floor}</td><td class="txtc">{media_name}</td><td class="txtc">{hours}</td><td class="txtc">{areas}</td><td class="txtc"><span class="glyphicon glyphicon-minus" title="删除"></span></td></tr>';
                    					$.each(data.resource, function(i,n){
                    						resourceArr.ids.pushOnly(n.resource_id+'');
                    						
                    						var _hours_edit = '', _areas_edit = '';
                    						if(semi.utils.isEmpty(n.hours)){
                    							_hours_edit = '默认';
                    						}else if(n.hours.length==24){
                    							_hours_edit = '全天';
                    			    		}else{
                    			    			_hours_edit = semi.utils.shorterNums(n.hours).join(',');
                    			    		}
                    						
                    						if(semi.utils.isEmpty(n.areas)){
                    							_areas_edit = '默认';
                    						}else{
                    							_areas_edit = n.areas.join(',');
                    			    		}
                    						
                    						resourceArr.nodes.push(_tmpl_media.replace('{resource_id}',n.resource_id).replace('{position_name}',n.position_name).replace('{start}',n.start).replace('{end}',n.end).replace('{width}',n.width).replace('{height}',n.height).replace('{max}',n.max).replace('{type}',n.type).replace('{floor}',n.floor).replace('{media_name}',n.media_name).replace('{hours}',_hours_edit).replace('{areas}',_areas_edit));
                    					});
                    					
                    					var $grid = $('.getresourcedata',$node).siblings('.checkedresource').show();
                                		$('tbody',$grid).empty();
                                		$.each(resourceArr.nodes, function(i,n){
                                			$('tbody',$grid).append(n);
                                			$('tbody tr:last',$grid).hoverClass('mouseover');
                                		});
                                		
                                		$('.getresourcedata',$node).siblings('[name=resourceids]').val(resourceArr.ids.join(','));
                    					
                                		//地域定向
                                		var _areasName = [];
                                		areaArr.submitNode = semi.utils.clone(data.areas);
                    					$.each(data.areas, function(i,n){
                    						_areasName.push(n.name);
                    					});
                    					$('.getareadata',$node).val(_areasName.join('，'));
                    					
                    					//关键字定向
                                		if(!semi.utils.isEmpty(data.words) && semi.utils.isEmpty(wordArr.data)){
                    						$ajax.ajax({
                    							url: requestUrl.getWord,
                    							success: function(treedata){
                    								$.each(data.words, function(i,n){
                    									var name = '';
                    									$.each(treedata.data, function(j,m){
                    										if(m.id==n.id)name=m.name;
                    									});
                    									wordArr.submitNode.push({id:n.id, name:name});
                    								});
                    								wordArr.data = treedata.data;
                    								$.each(wordArr.data, function(i,n){
                    									$.each(wordArr.submitNode, function(j,m){
                                            				if(n.id==m.id){
                                            					wordArr.submitNode[j]['pId'] = n.pId;
                                            				}
                                            			});
                                        			});
                    								var _wordsName = [], _ares = [], _words = []
                                            		$.each(areaArr.submitNode, function(i,n){
                                            			_ares.push(n.id);
                                					});
                                            		$.each(wordArr.submitNode, function(i,n){
                                            			var namepath = [n.name];
                                            			$.each(wordArr.data, function(j,m){
                                            				if(m.id==n.pId){
                                            					namepath.push(m.name);
                                            					$.each(wordArr.data, function(k,o){
                                                    				if(o.id==m.pId){
                                                    					namepath.push(o.name);
                                                    				}
                                                    			});
                                            				}
                                            			});
                                            			_wordsName.push(namepath.reverse().join('-'));
                                					});
                                					$('.getworddata',$node).val(_wordsName.join('，'));
                    							}
                        					});
                    					}
                    					
                    					//时间定向
                    					$('.gettimedata',$node).data('hours',data.hours);
                    					
                    					//算法选择
                    					//"{"a":"1","b":"1","c":[{"d":"2","e":""},{"d":"3","e":""},{"d":"4","e":""}]}"
                    					//algorithmArr.json = '{"a":"1","b":"1","c":[{"d":"2","e":""},{"d":"3","e":""},{"d":"4","e":""}]}';
                    					//algorithmArr.xml = '%3Cline%3E%0A%09%3Ctext%20width%3D%22%22%20align%3D%22left%22%20bold%3D%22true%22%3E%E8%BF%99%E6%98%AF%E4%B8%80%E4%B8%AA%E6%A0%87%E7%AD%BE%3C%2Ftext%3E%0A%09%3Ctextbox%20name%3D%22a%22%20width%3D%22%22%20type%3D%22%22%20default%3D%22%22%3Eplacehold%3C%2Ftextbox%3E%0A%09%3Ctext%20width%3D%22%22%20align%3D%22center%22%3Exxx%3C%2Ftext%3E%0A%09%3Cselect%20multi%3D%22%22%20name%3D%22b%22%20width%3D%22%22%20type%3D%22%22%20default%3D%22%22%20style%3D%22%22%3E%0A%09%09%3Coption%20value%3D%22%22%3E%E8%AF%B7%E9%80%89%E6%8B%A9%3C%2Foption%3E%0A%09%09%3Coption%20value%3D%221%22%3E1%3C%2Foption%3E%0A%09%3C%2Fselect%3E%0A%3C%2Fline%3E%0A%3Crepeat%20name%3D%22c%22%20min%3D%222%22%20max%3D%223%22%3E%0A%3Cline%3E%0A%09%3Ctext%20width%3D%22%22%20align%3D%22left%22%20bold%3D%22true%22%3E%E8%BF%99%E6%98%AF%E4%B8%80%E4%B8%AA%E6%A0%87%E7%AD%BE%3C%2Ftext%3E%0A%09%3Ctextbox%20name%3D%22d%22%20width%3D%22%22%20type%3D%22%22%20default%3D%22%22%3Eplacehold%3C%2Ftextbox%3E%0A%09%3Ctext%20width%3D%22%22%20align%3D%22center%22%20bold%3D%22false%22%3Exxx%3C%2Ftext%3E%0A%09%3Cselect%20multi%3D%22%22%20name%3D%22e%22%20width%3D%22%22%20type%3D%22%22%20default%3D%22%22%20style%3D%22%22%3E%0A%09%09%3Coption%20value%3D%22%22%3E%E8%AF%B7%E9%80%89%E6%8B%A9%3C%2Foption%3E%0A%09%3C%2Fselect%3E%0A%3C%2Fline%3E%3C%2Frepeat%3E';
                    					if(!semi.utils.isEmpty(data.alg)){
                    						algorithmArr.id = data.alg.id;
                    						algorithmArr.name = data.alg.name;
                    						algorithmArr.json = data.alg.parameters;
                    						algorithmArr.xml = data.alg.xml_format;
                    					}
                    					
                    					//素材选择 
                    					//var _tmpMaterial =[{name:'新分组1', weight:100, materials:[{id:21, landingpage:'www.baidu.com', name:'platform material 21', width:200, height:100, tags:['material tag 8','material tag 19']}]}]; 
                    					var _tmpl_material = '<tr material_id="{id}"><td class="txtc gname">{gname}</td><td class="txtr gweight">{gweight}</td><td class="txtl name">{name}</td><td class="txtc width">{width}</td><td class="txtc height">{height}</td><td class="txtc">{status}</td><td class="txtc"><a class="ibtn previewbtn" href="javascript:;" title="预览"><span class="glyphicon glyphicon-resize-full"></span></a><span class="glyphicon glyphicon-minus" title="删除"></td></tr>';
                    					var _html_material = '';
                    					$.each(data.group, function(i,n){
                    						var gname = n.name, gweight = n.weight;
                    						$.each(n.materials, function(k,m){
                    							var status = '';
                    							if(m.status==0){
                    								status = '<span class="label label-default">待审核</span>';
                    							}else if(m.status==1){
                    								status = '<span class="label label-success">通过</span>';
                    							}else{
                    								status = '<span class="label label-danger">拒绝</span>';
                    							}
                    							_html_material += (_tmpl_material.replace('{gname}',gname).replace('{gweight}',gweight).replaceAll('{id}', m.id).replaceAll('{name}', m.name).replaceAll('{width}', m.width).replaceAll('{height}', m.height).replaceAll('{status}', status))
                    							materialArr.materials.push({group:gname, weight:gweight, material_id:m.id+''});
                    						});
                    					});
                    					if(!semi.utils.isEmpty(_html_material)){
                                			var $grid_material = $('.checkedmaterial',$node).show();
                                			$('tbody',$grid_material).empty().append(_html_material);
                                			$('tbody tr:last',$grid_material).hoverClass('mouseover');
                                			$('.getmaterialdata',$node).siblings('[name=material]').val('hasmaterial');
                                		}else{
                                			$('.getmaterialdata',$node).siblings('[name=material]').val('');
                                		}
                    					materialArr.groups = data.group;
                    					//materialArr.materials = [{group:'新分组1', weight:100, material_id: 21}]
                    					
                    					/* 预览-dialog */
                    					require.async('./popmaterial', function($popmaterial){
                    						$popmaterial.init();
                    					});
                    					
                    					//站内平滑消耗开关
                    					if(data.consumeTypeIn){
                            				$('.consume_type_in .state_open',$node).addClass('btn-success').siblings('.btn').removeClass('btn-danger');
                            			}else{
                            				$('.consume_type_in .state_close',$node).addClass('btn-danger').siblings('.btn').removeClass('btn-success');
                            			}
                    					
                    					//站外平滑消耗开关
                    					if(data.consumeTypeOut){
                            				$('.consume_type_out .state_open',$node).addClass('btn-success').siblings('.btn').removeClass('btn-danger');
                            			}else{
                            				$('.consume_type_out .state_close',$node).addClass('btn-danger').siblings('.btn').removeClass('btn-success');
                            			}
                    					
                    					//联盟平滑消耗开关
                    					if(data.consumeTypeAlly){
                            				$('.consume_type_ally .state_open',$node).addClass('btn-success').siblings('.btn').removeClass('btn-danger');
                            			}else{
                            				$('.consume_type_ally .state_close',$node).addClass('btn-danger').siblings('.btn').removeClass('btn-success');
                            			}
                    					
                                		$node.initUI();
                                		initDialog();
                    				}
                    			});
                    			return;
                    		}else if(!semi.utils.isEmpty(op.traffic_id)){
                    			$ajax.ajax({
			                		url: requestUrl.getOneInfo,
			                		data: JSON.stringify({
			                			traffic_id: op.traffic_id
			                		}),
		                    		contentType : "application/json",
		                            type : 'POST',
		                            dataType : 'json',
			                		success: function(data){
			                			$d.content(popTmpl);
			                			$('[name=circle]',$node).val(data.start+' 至 '+data.end);
			                			//媒体定向 
                    					//var _tmpResource = [{resource_id:50, position_name:'media 5 position 10', start:'2014-01-01', end:'2014-12-31', width:'200', height:'100', type:'PNG、JPG、GIF、BMP', floor:'1', media_name:'media 5'}]
                    					var _tmpl_media = '<tr resource_id="{resource_id}"><td class="txtc"><span class="glyphicon glyphicon-ok green" title="有效分片"></span></td><td class="txtc">{position_name}</td><td class="txtc range">{start} 至 {end}</td><td class="txtc width">{width}</td><td class="txtc height">{height}</td><td class="txtc max">{max}</td><td class="txtc type">{type}</td><td class="txtc">{floor}</td><td class="txtc">{media_name}</td><td class="txtc">{hours}</td><td class="txtc">{areas}</td><td class="txtc"><span class="glyphicon glyphicon-minus" title="删除"></span></td></tr>';
                    					$.each(data.resource, function(i,n){
                    						resourceArr.ids.pushOnly(n.resource_id+'');
                    						
                    						var _hours_edit = '', _areas_edit = '', _areasName = [];
                    						if(semi.utils.isEmpty(n.hours)){
                    							_hours_edit = '默认';
                    						}else if(n.hours.length==24){
                    							_hours_edit = '全天';
                    			    		}else{
                    			    			_hours_edit = semi.utils.shorterNums(n.hours).join(',');
                    			    		}
                    						
                    						if(semi.utils.isEmpty(n.areas)){
                    							_areas_edit = '默认';
                    						}else{
                    			    			$.each(n.areas, function(i,n){
                    			    				_areasName.push(n.name);
                    			    			});
                    			    			_areas_edit = _areasName.join(',');
                    			    		}
                    						resourceArr.nodes.push(_tmpl_media.replace('{resource_id}',n.resource_id).replace('{position_name}',n.position_name).replace('{start}',n.start).replace('{end}',n.end).replace('{width}',n.width).replace('{height}',n.height).replace('{max}',n.max).replace('{type}',n.type).replace('{floor}',n.floor).replace('{media_name}',n.media_name).replace('{hours}',_hours_edit).replace('{areas}',_areas_edit));
                    					});
                    					var $grid = $('.getresourcedata',$node).siblings('.checkedresource').show();
                                		$('tbody',$grid).empty();
                                		$.each(resourceArr.nodes, function(i,n){
                                			$('tbody',$grid).append(n);
                                			$('tbody tr:last',$grid).hoverClass('mouseover');
                                		});
                                		
                                		$('.getresourcedata',$node).siblings('[name=resourceids]').val(resourceArr.ids.join(','));
                                		$node.initUI();
                                		initDialog();
			                		}
		                		});
                    			return;
                    			
                    		}else if(!semi.utils.isEmpty(op.resource_id)){
                    			$ajax.ajax({
			                		url: requestUrl.getOneInfo,
			                		data: JSON.stringify({
			                			resource_id: op.resource_id
			                		}),
		                    		contentType : "application/json",
		                            type : 'POST',
		                            dataType : 'json',
			                		success: function(data){
			                			var _resource = data.resource[0];
			                			seajs.log(data);
			                			$d.content(popTmpl);
			                			$('[name=circle]',$node).val(_resource.start+' 至 '+_resource.end);
			                			//地域定向
                                		var _areasName = [];
                                		areaArr.submitNode = semi.utils.clone(_resource.areas);
                    					$.each(_resource.areas, function(i,n){
                    						_areasName.push(n.name);
                    					});
                    					$('.getareadata',$node).val(_areasName.join('，'));
			                			//媒体定向 
                    					//var _tmpResource = [{resource_id:50, position_name:'media 5 position 10', start:'2014-01-01', end:'2014-12-31', width:'200', height:'100', type:'PNG、JPG、GIF、BMP', floor:'1', media_name:'media 5'}]
                    					var _tmpl_media = '<tr resource_id="{resource_id}"><td class="txtc"><span class="glyphicon glyphicon-ok green" title="有效分片"></span></td><td class="txtc">{position_name}</td><td class="txtc range">{start} 至 {end}</td><td class="txtc width">{width}</td><td class="txtc height">{height}</td><td class="txtc max">{max}</td><td class="txtc type">{type}</td><td class="txtc">{floor}</td><td class="txtc">{media_name}</td><td class="txtc">{hours}</td><td class="txtc">{areas}</td><td class="txtc"><span class="glyphicon glyphicon-minus" title="删除"></span></td></tr>';
                    					$.each(data.resource, function(i,n){
                    						resourceArr.ids.pushOnly(n.resource_id+'');
                    						
                    						var _hours_edit = '', _areas_edit = '', _areasName = [];
                    						if(semi.utils.isEmpty(n.hours)){
                    							_hours_edit = '默认';
                    						}else if(n.hours.length==24){
                    							_hours_edit = '全天';
                    			    		}else{
                    			    			_hours_edit = semi.utils.shorterNums(n.hours).join(',');
                    			    		}
                    						
                    						if(semi.utils.isEmpty(n.areas)){
                    							_areas_edit = '默认';
                    						}else{
                    			    			$.each(n.areas, function(i,n){
                    			    				_areasName.push(n.name);
                    			    			});
                    			    			_areas_edit = _areasName.join(',');
                    			    		}
                    						resourceArr.nodes.push(_tmpl_media.replace('{resource_id}',n.resource_id).replace('{position_name}',n.position_name).replace('{start}',n.start).replace('{end}',n.end).replace('{width}',n.width).replace('{height}',n.height).replace('{max}',n.max).replace('{type}',n.type).replace('{floor}',n.floor).replace('{media_name}',n.media_name).replace('{hours}',_hours_edit).replace('{areas}',_areas_edit));
                    					});
                    					var $grid = $('.getresourcedata',$node).siblings('.checkedresource').show();
                                		$('tbody',$grid).empty();
                                		$.each(resourceArr.nodes, function(i,n){
                                			$('tbody',$grid).append(n);
                                			$('tbody tr:last',$grid).hoverClass('mouseover');
                                		});
                                		
                                		$('.getresourcedata',$node).siblings('[name=resourceids]').val(resourceArr.ids.join(','));
			                			
			                			//时间定向
                    					$('.gettimedata',$node).data('hours',_resource.hours);
                    					$node.initUI();
                                		initDialog();
			                		}
		                		});
                    			return;
                    		}
            				
                    		$d.content(popTmpl);
                    		$node.initUI();
                    		initDialog();
            			},
            			error: function(){
            				
            			}
            		});
            	}
            }
    	if(!op.isview){
    		$.extend(defOp, {
            	okValue: '确定',
            	ok: function(){
            		var $d = this, $node = $(this.node);
            		require.async('validate', function(){
            			$.each(resourceArr.badids, function(i,n){
            				$('.checkedresource tr[resource_id='+n+']',$node).find('.glyphicon-minus').click();
            			});
            			if(!$('form',$node).valid())return false;
            			
            			var $landingpage = $('[name=landingPage]',$node),
            				landingPage = $landingpage.val();
            			if(!semi.utils.isEmpty(landingPage) && !semi.utils.isGomeUrl(landingPage)){
            				$landingpage.addClass('error').siblings('label.error').remove();
            				$landingpage.after('<label class="error">请填写国美站内链接</label>');
            			}else{
            				$landingpage.removeClass('error').siblings('label.error').remove();
            			}
                		if($landingpage.hasClass('error')){
                			return false;
                		}
                		var range = $('[name=circle]',$node).val().split(' 至 ');
                		var _ares = [], _words = [], _materials = [];
                		$.each(areaArr.submitNode, function(i,n){
                			_ares.push(n.id);
    					});
                		$.each(wordArr.submitNode, function(i,n){
                			var namepath = [n.name];
                			$.each(wordArr.data, function(j,m){
                				if(m.id==n.pId){
                					namepath.push(m.name);
                					$.each(wordArr.data, function(k,o){
                        				if(o.id==m.pId){
                        					namepath.push(o.name);
                        				}
                        			});
                				}
                			});
                			_words.push({id:n.id, name:namepath.reverse().join('&')});
    					});
                		$.each(materialArr.groups, function(i,n){
    						var gname = n.name, gweight = Math.round(n.weight*100/n.materials.length);
    						$.each(n.materials, function(k,m){
    							_materials.push({group:gname, weight:gweight, material_id:m.id});
    						});
    					});
                		
                		var data = {
                				name: $('[name=name]',$node).val(),
                				dailyAmountIn: $('[name=dailyAmountIn]',$node).val(),
                				dailyAmountOut: $('[name=dailyAmountOut]',$node).val(),
                				dailyAmountAlly: $('[name=dailyAmountAlly]',$node).val(),
                				totalAmountIn: $('[name=totalAmountIn]',$node).val(),
                				totalAmountOut: $('[name=totalAmountOut]',$node).val(),
                				totalAmountAlly: $('[name=totalAmountAlly]',$node).val(),
                				landingPage: encodeURIComponent($('[name=landingPage]',$node).val()),
                				start: range[0],
                				end: range[1],
                				hours: $('.gettimedata',$node).data('hours'),
                				resource: resourceArr.ids,
                				areas: _ares,
                				words: _words,
                				materials: _materials,
                				consume_type_in: $('.consume_type_in .state_open',$node).hasClass('btn-success')?1:0,
                				consume_type_out: $('.consume_type_out .state_open',$node).hasClass('btn-success')?1:0,
                				consume_type_ally: $('.consume_type_ally .state_open',$node).hasClass('btn-success')?1:0
                						
                			}
                		if(!isplatform){
                			var $formate = require('./formatxml');
                    		algorithmArr.json = JSON.stringify($formate.getjson($('.checkedalgorithm .uicontent',$node)));
                			$.extend(data,{
                				price: $('[name=price]',$node).val(),
                				dailyBudgetAlly: $('[name=dailyBudgetAlly]',$node).val(),
                				dailyBudgetIn: $('[name=dailyBudgetIn]',$node).val(),
                				dailyBudgetOut: $('[name=dailyBudgetOut]',$node).val(),
                				totalBudgetIn: $('[name=totalBudgetIn]',$node).val(),
                				totalBudgetOut: $('[name=totalBudgetOut]',$node).val(),
                				totalBudgetAlly: $('[name=totalBudgetAlly]',$node).val(),
        						algorithm: algorithmArr.id,
                				parameters: algorithmArr.json
                			});
        				}
                		if(isedit){
                			$.extend(data,{
                				id: strategy_id
                			});
            	    	}
                		$ajax.ajax({
                			url: requestUrl.submit,
                			data: JSON.stringify(data),
                    		contentType : "application/json",
                            type : 'POST',
                            dataType : 'json',
                			success: function(data){
            					$d.close().remove();
            					$dialog.alert((isedit?'修改':'新建')+'策略成功！','success');
            					if(!semi.utils.isEmpty(op.success) && $.isFunction(op.success))op.success.call(this, data);
                			},
                			error: function(data){
                				$dialog.alert((isedit?'修改':'新建')+'策略失败,请稍后重试！','warning');
                				if(!semi.utils.isEmpty(op.error) && $.isFunction(op.error))op.error.call(this, data);
                			}
                		});
            		});
                	return false;
                },
                cancelValue: '取消',
                cancel: true
    		});
    	}else{
    		$.extend(defOp, {
                cancelValue: '关闭',
                cancel: true
    		});
    	}
    	var $dlg = $dialog(defOp).showModal();
	}
	
	
	var addStrategy  = function(option){
		var op = $.extend({
			type: '',
			action: 'add'
		}, option);
		
		popStrategy(op);
	}
	
	var editStrategy  = function(option){
		var op = $.extend({
			type: '',
			strategy_id: '',
			action: 'edit',
			isview: false,
			state: ''
		}, option);
		
		if(semi.utils.isEmpty(op.strategy_id))return;
		popStrategy(op);
	}
	
	return{
		add: addStrategy,
		edit: editStrategy
	}
});